import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { AcquisitionManageContext, IAcquisitionActionEnum } from '.';
import { materialTableService } from '../services/ModalServices';
import { CompressOutlined, ExpandOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import { getLoadMapList, getTenantID, getPosIDs, getUserID, onCloseModalCommon, getUserDepID } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { UpdateTableCommon } from './UpdateTableCommon';
import { AssetacquisitionManageAPI } from '../common/type';
import { getReturnAssetModalColumns, getUseAssetModalColumns } from './ModalColumns';
import _ from 'lodash';
import { ILoadMapTypeAll } from '@/common';
import { LYflowBusinessType } from '../common/FormatUse';
import '../common/style.less';

/** 领用/退库 表单页 选择资产-模态框 */
export const OpenAssetModal: React.FC<AssetacquisitionManageAPI.IOpenMaterialModal> = ({
  onClose,
  isShowModal,
  queryType = '1',
  editState,
  editAssetId,
  handleEditSave,
  detailInfo,
  BelongDepartmentID,
}) => {
  /** 货物归属部门ID */
  const [belongID, setBelongID] = useState();

  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);

  /**管理页Ref*/
  const ManagePageRef = useRef<Record<string, any>>(null);

  useEffect(() => {
    if (belongID && ManagePageRef?.current?.getSearchRun) {
      if (belongID === getUserDepID()) {
        ManagePageRef?.current?.getSearchRun({ sharing: '0' });
      } else {
        ManagePageRef?.current?.getSearchRun({ sharing: '1' });
      }
    }
  }, [belongID, ManagePageRef]);

  /** 根样式 */
  const styleFixCls = 'contract-styfixcls-';

  /** 获取上下文 */
  const { curRes, acquisitionDispatch, assetList } = useContext(AcquisitionManageContext);

  /** 获取列表 */
  const { dataList, data, params, loading, pagination, searchList, loadMdicMapObj, getManageData } = materialTableService(
    curRes,
    1,
    queryType,
    editState,
    belongID,
    editAssetId,
  );

  /** 解析保存货物归属部门ID */
  useEffect(() => {
    BelongDepartmentID()?.then((res) => {
      setBelongID(res);
      // if (res) {
      //   getManageData({ createDepartmentID: res });
      // }
    });
  }, [BelongDepartmentID]);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //单位
  ]);

  /**  获取数据字典 */
  const midiList = loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`];

  /** 暂时保存选中的值 */
  const [checkAssetList, setCheckAssetList] = useState<Record<string, any>[]>([]);

  /** 是否全屏 */
  const [isAll, setIsAll] = useState<boolean>(false);

  /** 表格数据 */
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);

  useEffect(() => {
    if (dataList?.length) {
      let dataRow: Record<string, any>[] = [];
      dataRow = _.cloneDeep(data?.rows);
      // 添加总价和数量字段
      for (let i = 0; i < dataRow.length; i++) {
        dataRow[i].quantityOrArea = dataRow[i].hasOwnProperty('residueNum') ? dataRow[i].residueNum : dataRow[i].quantityOrArea;
        dataRow[i].materialOrAssetId = dataRow[i].id;

        dataRow[i].location = '';
        dataRow[i].locationInfo = '';
        dataRow[i].locationName = '';
      }

      if (assetList.length !== 0) {
        for (let i = 0; i < assetList.length; i++) {
          let idx = dataRow.findIndex((item: Record<string, any>) => {
            return item.materialOrAssetId === assetList[i].materialOrAssetId;
          });
          if (idx !== -1) {
            dataRow[idx].quantityOrArea = Number(assetList[i].quantityOrArea);
            dataRow[idx].location = assetList[i].location;
            dataRow[idx].locationInfo = assetList[i].locationInfo;
            dataRow[idx].locationName = assetList[i].locationName;
          }
        }
      }
      setDataSource(dataRow);
    } else {
      setDataSource([]);
    }
  }, [dataList]);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload, current: 1 });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    // getManageData({ ...payload });
    if (belongID && ManagePageRef?.current?.getSearchRun) {
      if (belongID === getUserDepID()) {
        ManagePageRef?.current?.getSearchRun({ sharing: '0' });
      } else {
        ManagePageRef?.current?.getSearchRun({ sharing: '1' });
      }
    }
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    const tempArr = _.cloneDeep(dataSource);
    for (let i = 0; i < tempArr.length; i++) {
      tempArr[i].selected = selectInfo?.some((item) => item.id === tempArr[i].id);
    }
    setDataSource(tempArr);
    setCheckAssetList(selectInfo);
  };

  /** 初始化 */
  useEffect(() => {
    if (editState) {
      if (editAssetId?.text && Object.keys(editAssetId?.text).length !== 0) {
        let arr: Record<string, any>[] = [];
        for (let i = 0; i < Object.keys(editAssetId?.text).length; i++) {
          let idx: number = dataSource.findIndex((item: any) => {
            return item.id === Object.keys(editAssetId?.text)[i];
          });
          if (idx !== -1) {
            arr.push(dataSource[idx]);
          }
        }
        setCheckAssetList(arr);
      } else {
        setCheckAssetList([]);
      }
    } else {
      setCheckAssetList(assetList);
    }
  }, [isShowModal, loading]);

  /** 修改资产数量 */
  const changeNum = (id: string | number, value: string | number) => {
    /** 修改表格数量 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.id === id;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].quantityOrArea = value;
      setDataSource(arr);
    }

    /** 修改选中数量 */
    let checkIdx = checkAssetList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkAssetList);
      arr[checkIdx].quantityOrArea = value;
      if (arr[checkIdx].residueNum) {
        arr[checkIdx].expectNum = arr[checkIdx].residueNum - arr[checkIdx].quantityOrArea;
      } else {
        arr[checkIdx].expectNum = dataSource[checkIdx].residueNum - arr[checkIdx].quantityOrArea;
      }

      setCheckAssetList(arr);
    }
  };

  const batchSyncData = (text, record) => {
    let arrData = _.cloneDeep(dataSource);
    arrData?.map((item: Record<string, any>) => {
      let arr = checkAssetList.find((i) => {
        return i.id == item.id;
      });
      if (arr && !item[text]) {
        item[text] = record[text];
      }
    });
    setDataSource(arrData);

    let arrChecked = _.cloneDeep(checkAssetList);
    arrChecked?.map((item: Record<string, any>) => {
      if (!item[text]) item[text] = record[text];
    });
    setCheckAssetList(arrChecked);
  };

  /** 修改存放地点 */
  const changeLocation = (id: string | number, value: string) => {
    /** 修改表格存放地点 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].location = value;
      setDataSource(arr);
    }

    /** 修改选中存放地点 */
    let checkIdx = checkAssetList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkAssetList);
      arr[checkIdx].location = value;
      setCheckAssetList(arr);
    }
  };

  /** 修改详细地址 */
  const changeLocationInfo = (id: string | number, value: string) => {
    /** 修改表格存放地点 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].locationInfo = value;
      setDataSource(arr);
    }

    /** 修改选中存放地点 */
    let checkIdx = checkAssetList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkAssetList);
      arr[checkIdx].locationInfo = value;
      setCheckAssetList(arr);
    }
  };

  /** 点击确定 */
  const onSave = () => {
    if (checkAssetList && checkAssetList?.length > 0) {
      const taskType: string = LYflowBusinessType();
      const taskHandInfo: Record<string, any> = detailInfo?.paramObject?.[taskType];
      // 复核中选中的
      if (
        (detailInfo?.queryType == '1' || detailInfo?.queryType == '3') &&
        taskHandInfo &&
        taskHandInfo?.mactivitiTaskList?.length > 0 &&
        taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
        taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID() &&
        detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1006`
      ) {
        acquisitionDispatch({
          type: IAcquisitionActionEnum.SELECT_ASSET,
          payload: checkAssetList,
        });
        handleEditSave(checkAssetList);
        onCloseModalCommon(updateModalRef);
      } else {
        acquisitionDispatch({
          type: IAcquisitionActionEnum.SELECT_ADD_ASSET,
          payload: checkAssetList,
        });
        // 存储到仓库
        acquisitionDispatch({
          type: IAcquisitionActionEnum.SELECT_ASSET,
          payload: [...checkAssetList],
        });
        onCloseModalCommon(updateModalRef);
      }
    } else {
      message.error('请至少选择一个资产');
    }
  };

  const [isNextBtn, setisNextBtn] = useState(true);

  const setisNextBtnFun = (isNextBtn: boolean) => {
    setisNextBtn(isNextBtn);
  };

  const desabledNextBtn = useMemo(() => {
    if (queryType == '1' || queryType == '3') {
      // 如果是复核中，则没有存放区域校验
      if (editState) {
        if (checkAssetList?.length != 0) {
          return false;
        } else {
          return true;
        }
      } else {
        if (
          checkAssetList?.length != 0 &&
          checkAssetList?.every((item: Record<string, any>) => item.location) &&
          checkAssetList?.every((item: Record<string, any>) => item.locationInfo) &&
          isNextBtn
        ) {
          return false;
        } else {
          return true;
        }
      }
    } else {
      if (checkAssetList?.length != 0) {
        return false;
      } else {
        return true;
      }
    }
  }, [checkAssetList, isNextBtn, editState, dataSource]);

  const modelFooter = () => {
    return (
      <>
        <Button onClick={onSave} disabled={desabledNextBtn}>
          确定
        </Button>
      </>
    );
  };

  /** 表格行配置 */
  const getTable: any = useMemo(() => {
    if (queryType == '1' || queryType == '3') {
      return getUseAssetModalColumns({
        batchSyncData,
        changeLocation,
        changeLocationInfo,
        changeNum,
        setisNextBtnFun,
        queryType: '1',
        editState,
        mapLoading,
        loadMapInfo,
        midiList,
      });
    } else {
      return getReturnAssetModalColumns({
        batchSyncData,
        changeLocation,
        changeLocationInfo,
        changeNum,
        setisNextBtnFun,
        queryType: '2',
        editState,
        mapLoading,
        loadMapInfo,
        midiList,
      });
    }
  }, [assetList, queryType, editState, loadMapInfo, midiList, checkAssetList]);

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={
          <div>
            <span>选择资产</span>
            <span
              style={{ float: 'right', marginRight: 30, cursor: 'pointer' }}
              onClick={() => {
                setIsAll(!isAll);
              }}
            >
              {isAll ? <CompressOutlined /> : <ExpandOutlined />}
            </span>
          </div>
        }
        onCancel={onClose}
        width={document.body.clientWidth * (isAll ? 1.0 : 0.85)}
        bodyStyle={{
          height: document.body.clientHeight * (isAll ? 0.85 : 0.65),
          padding: 10,
        }}
        // onOk={onSave}
        footer={modelFooter()}
      >
        <div className="asset_apply_selectAssetModalBox">
          <UpdateTableCommon
            ref={ManagePageRef}
            styleFixCls={styleFixCls}
            searchProps={{
              searchList,
              onReset,
              onSearch,
            }}
            selectTablePorps={{
              onSelectTable,
              selectRowObjList: checkAssetList,
              selectType: 'checkbox',
              setCheckRows: setCheckAssetList,
              getCheckboxProps: (record: Record<string, any>) => ({
                disabled: record.quantityOrArea <= 0,
              }),
            }}
            tableProps={{
              columns: getTable,
              loading,
              dataSource: dataSource,
              pagination,
              onPageChange,
              rowKey: 'materialOrAssetId',
              tableTotalShow: (total: any, range: any) => {
                return (
                  <div
                    style={{
                      display: 'flex',
                      width: '100%',
                      justifyContent: 'space-between',
                    }}
                  >
                    <div>
                      已选择<strong style={{ color: 'red' }}> {checkAssetList?.length} </strong>条材料
                    </div>
                    <div>{showTotalInfo(total, range)}</div>
                  </div>
                );
              },
            }}
          />
        </div>
      </OneModal>
    </>
  );
};
